package com.loopy.fruns.dao;

import com.loopy.fruns.utils.JDBCDruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class BasicDAO<T> {
    private QueryRunner queryRunner= new QueryRunner();

    public int update(String sql,Object...parameters){
        Connection connection=null;
        try {
            connection= JDBCDruidUtils.getConnection();
            int update = queryRunner.update(connection, sql, parameters);
            return update;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public List<T> Multi(String sql, Class<T> clazz, Object...parameters){
        Connection connection=null;
        try {
            connection = JDBCDruidUtils.getConnection();
            List<T> list = queryRunner.query(connection, sql, new BeanListHandler<>(clazz), parameters);
            return list;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    public T QuerySingle(String sql,Class<T> clazz,Object... parameters){
        Connection connection=null;
        try {
            connection = JDBCDruidUtils.getConnection();
            T query = queryRunner.query(connection, sql, new BeanHandler<>(clazz), parameters);
            return query;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Object QueryScalar(String sql,Object... parameters){
        Connection connection=null;
        try {
            connection = JDBCDruidUtils.getConnection();
            Object query = queryRunner.query(connection, sql, new ScalarHandler(), parameters);
            return query;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
